import asyncio
import websockets
import speech_recognition as sr
import datetime

# 映射关键词到数字
keyword_map = {
    "第一款产品": "1",
    "第二款产品": "2",
    "第三款产品": "3",
    "第四款产品": "4",
    "第五款产品": "5"
}

# 调试日志函数
def log_debug(message):
    timestamp = datetime.datetime.now().strftime("%H:%M:%S")
    print(f"[DEBUG {timestamp}] {message}")

# WebSocket服务端
async def handler(websocket, path):
    client_ip = websocket.remote_address[0]
    client_port = websocket.remote_address[1]
    log_debug(f"客户端已连接: {client_ip}:{client_port}")
    
    recognizer = sr.Recognizer()
    mic = sr.Microphone()

    with mic as source:
        recognizer.adjust_for_ambient_noise(source)
        log_debug("🎤 开始监听，请说'第一段'、'第二段'...")
        
        try:
            while True:
                try:
                    audio = recognizer.listen(source, timeout=5)
                    text = recognizer.recognize_google(audio, language="zh-CN")
                    log_debug(f"👂 识别到: {text}")

                    # 检查每个关键词
                    keyword_found = False
                    for k, v in keyword_map.items():
                        if k in text:
                            log_debug(f"✅ 触发关键词: {k} -> 发送 {v}")
                            await websocket.send(v)
                            keyword_found = True
                            break
                    
                    if not keyword_found:
                        log_debug("⚠️ 未检测到预定义关键词")

                except sr.WaitTimeoutError:
                    # 超时是正常的，继续监听
                    continue
                except sr.UnknownValueError:
                    log_debug("⚠️ 无法识别的语音")
                    continue
                except sr.RequestError as e:
                    log_debug(f"⚠️ 语音识别服务错误: {e}")
                    await asyncio.sleep(1)  # 避免快速重试
                except websockets.exceptions.ConnectionClosed as e:
                    log_debug(f"⚠️ 客户端断开连接: {e.code} - {e.reason}")
                    break
                except Exception as e:
                    log_debug(f"⚠️ 发生错误: {type(e).__name__} - {str(e)}")
                    await asyncio.sleep(1)  # 避免快速重试
        finally:
            log_debug("👋 监听已停止")

# 启动WebSocket服务（端口 8765）
async def main():
    try:
        async with websockets.serve(handler, "localhost", 8765):
            log_debug("🚀 WebSocket监听服务已启动 ws://localhost:8765")
            await asyncio.Future()  # 保持服务运行
    except Exception as e:
        log_debug(f"❌ 无法启动WebSocket服务: {e}")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        log_debug("🛑 服务已被用户中断")
    except Exception as e:
        log_debug(f"💥 程序异常终止: {e}")
